import type { _AsyncData } from 'nuxt/dist/app/composables/asyncData';
import { ElMessage } from 'element-plus';

export const myRequest: any = (url: string, options?: any): Promise<any> => {
  const store = useNuxtStore()
  const TOKEN = store.token
  let baseUrl = useRuntimeConfig().public.apiBase; // 这个是 请求的接口
  let reqUrl = `${baseUrl}/api${url}`
  return new Promise((resolve, reject) => {
    useFetch(reqUrl, { 
      ...options,
      // 设置请求标头  下次出现跨域问题，请考虑这个 onRequest
      onRequest({ request, options }) {
        options.headers = options.headers || {};
        (options.headers as any).Authorization = TOKEN || null;
      },
      // 处理请求错误
      onRequestError({ request, options, error }) {
        ElMessage({
          message: "请求出现错误，请联系客服",
          type: 'error',
        })
        return Promise.reject(error)
      },
      // 处理响应数据
      onResponse({ request, response, options }) {
        if (response.status == 404 || response.status == 502) {
          ElMessage({
            message: response.status as unknown as string,
            type: 'error',
            duration: 1 * 1000
          })
          return false;
        }
        const res = response._data
        if (res.code == 80001) {
          ElMessage({
            message: '登录已过期，请重新登录！',
            type: 'warning',
            duration: 2 * 1000
          })
          return response;
        } else if (res.code == 0) {
          return response;
        } else if (res.code == 10001) {
          // 跳转404
          navigateTo('/404')
          return false;
        }
      },
      // 处理响应错误
      onResponseError({ request, response, options }) {
        ElMessage({
          message: `${response.status} ${response.statusText} 请联系客服！`,
          type: 'error',
          duration: 3 * 1000
        })
        if (response.status != 200) {
          return false;
        }
        return Promise.reject(Error)
      }
    }).then(({ data, error }: any) => {
      if (error.value) {
        reject(error.value)
        return
      }
      const value = data._value
      resolve(ref(value))
    }).catch((err: any) => {
      reject(err)
    })
  })
}
